<?php

require_once("redbean/redbean.php");
require_once("lib/configurationmanager.php");
R::setup();


class RBDB
{
	/**
	 * Returns a redbean toolbox
	 */
	public function toolbox()
	{
		static $toolbox = null;
		if(!$toolbox)
		{
			$conf = new ConfigurationManager();
			$conf->load();

			$toolbox = RedBean_Setup::kickstartDev(
				$conf->dsn,
				$conf->username,
				$conf->password);
		}

		return $toolbox;

	}

	/**
	 * Returns a redbean object
	 */
	public function redbean()
	{
		return self::toolbox()->getRedBean();
	}

	public function databaseAdapter()
	{
		return self::toolbox()->getDatabaseAdapter();
	}

}

// Call toolbox at least once so RedBean
// knows it should use dsn defined in config.
RBDB::toolbox(); 

/**
 * The abstract model every model will be derived from. Has simple __get and 
 * __set overrides so $model->foo = "bar" will actually write "bar" in a "foo" 
 * column to model's table (after a $model->save()). 
 */
class RedBeanModel extends RedBean_DomainObject
{
	/**
	 * Mixed param can be
	 *  - empty: create new bean
	 *  - integer: the ID of the bean that will be loaded
	 *  - bean: the bean that will be loaded
	 */
	public function __construct($param = 0)
	{
		if(is_integer($param))
		{
			$id = $param;
			if($id == 0)
			{
				// Make new bean
				return parent::__construct(strtolower(get_class($this)));
			}
			else
			{
				// Load existing bean by id
				$this->find($id);
			}
		}
		else
		{
			// Assume the parameter contains a bean, load this
			$this->loadBean($param);
		}
	}

	public function __set($key, $val)
	{
		$this->bean->$key = $val;
	}

	public function __get($key)
	{
		return $this->bean->$key;
	}
}

?>
